<?php
set_time_limit(0);

require_once 'vendor/autoload.php';
require_once 'config.php';

use Elasticsearch\ClientBuilder;
use Elasticsearch\Common\Exceptions\Missing404Exception;


class Document
{
    private $client = null;

    public function __construct() {
        $this->client = ClientBuilder::create()
            ->setHosts([SEARCH_URL])
            ->build();
    }

    public function save($pattern) {
        $data = array(
            'pid' => $pattern['pid'],
            'is_public' => $pattern['is_public'],
            'content' => '',
            'picture' => $pattern['picture'],
            'picture_thumb' => $pattern['picture_thumb'],
            'weight' => $pattern['weight'],
            'height' => $pattern['height'],
            'widthheight' => $pattern['widthheight'],
            'widthlow' => $pattern['widthlow'],
            'no' => $pattern['no'],
            'component' => $pattern['component'],
            'series' => $pattern['series'],
            'level' => $pattern['level'],
            'viewId'=> $pattern['viewId'],
        );

        // 处理封板================= begin =========================
        $plates_out = [];
        $plates = json_decode($pattern['plates'], true);

        foreach ($plates as $plate) {
            if (count($plate) == 1) {
                $plates_out[] = $plate[0] . $plate[0];
            } else {
                $plates_out[] = implode(',', $plate);
            }
        }

        if (count($plates_out) > 0) {
//        $data['sealing'] = implode("|", $plates_out);
            $data['sealing'] = $plates_out;
        } else {
            $data['sealing'] = [];
        }
        // 处理封板=================== end ===========================

        // 设置属性
        $properties = $pattern['properties'];
        $property_strings = '';

        // 属性字段拼接
        if ($properties != null) {
            foreach ($properties as $property) {
                $json = json_decode($property['property_value'], true);
                $value = $json['value'];

                if (is_array($value)) {
                    $property_strings .= ' ' . implode(',', $value);
                } else {
                    $property_strings .= ' ' . $value;
                }
            }
        }

        $data['content'] .= $pattern['no'] . $property_strings;


        $param = [
            'index' => 'pattern',
            'id' => $pattern['no'],
            'body' => $data
        ];
        
        try {
            $this->client->index($param);
        } catch (Exception $exception) {
            print_r($exception);
        }
    }

    public function delete($no) {
        $params = [
            'index' => 'pattern',
            'id' => $no
        ];

        try {
            if ($this->client->delete($params)) {
                return true;
            }

            return false;
        } catch (Missing404Exception $exception) {
            return false;
        }
    }

    public function search($keywords, $rules, $limit, $page = 1, $ids = array()) {
        $param = [
            'index' => 'pattern',
            'body'=>[
                'query'=> [
                    'bool' => [
                        'must' => [
                            ['term' => ['is_public' => '1']],
                        ],
                    ],
                ]
            ],
            'from' => ($page - 1) * $limit,
            'size' => $limit,
//            '_source' => ['content']
        ];

        // 处理ids
        if (!empty($ids)) {
            // $param['body']['query']['bool']['must'][] = ['ids' => ['values' => $ids]];
            $param['body']['query']['bool']['must'][] = ['terms'=>['no'=>$ids]];

            $map = [];

            foreach ($ids as $i => $id) {
            	$map[$id] = count($ids) - $i;
            }

	        $param['body']['sort']["_script"] = [
		        'script' => [
			        "lang" => "painless",
			        "source" => "if(params.scores.containsKey(doc['no'].value)) { return params.scores[doc['no'].value];} return 100000;",
			        "params" => [
				        "scores" => $map
			        ]
		        ],
		        "type" => "number",
		        "order" => "desc"
	        ];
        }

        // var_dump($keywords);
        // 处理关键词改成模糊搜索
        foreach ($keywords as $keyword) {
            // var_dump(strtolower($keyword));
            if (!is_array($keyword)) {
                // var_dump(11);
                if (ctype_alnum($keyword)) {        
                    $param['body']['query']['bool']['must'][] =['wildcard' => ['content' => ['wildcard' => '*'.strtolower($keyword).'*']] ];
                } else {         
                    $param['body']['query']['bool']['must'][] = ['match_phrase' => ['content' => $keyword]];
                }
                
                // $param['body']['query']['bool']['must'][] = ['match_phrase' => ['content' => $keyword]];
                // $param['body']['query']['bool']['must'][] = ['wildcard' => ['content' =>'*'.strtolower($keyword).'*']];
                // $param['body']['query']['bool']['must'][] =['wildcard' => ['content' => ['wildcard' => '*'.strtolower($keyword).'*']] ];
                // $param['body']['query']['bool']['must'][] = ['match_phrase_prefix' => ['content' => ['query' => $keyword,'max_expansions'=>50]] ];
            } else {
                if ($keyword['type'] == 'AND') {
                    // var_dump(22);
                    foreach ($keyword['keywords'] as $item) {
                        $param['body']['query']['bool']['must'][] = ['match_phrase' => ['content' => $item]];
                        // $param['body']['query']['bool']['must'][] =['wildcard' => ['content' => ['value' => '*'.strtolower($item).'*']] ];
                        // $param['body']['query']['bool']['must'][] = ['match_phrase_prefix' => ['content' => ['query' => $item,'max_expansions'=>50]] ];
                    }
                } else {
                    // var_dump(33);
                    $condition = [
                        'bool' => [
                            'should' => []
                        ]
                    ];

                    foreach ($keyword['keywords'] as $item) {
                        $condition['bool']['should'][] = ['match_phrase' => ['content' => $item]];
                        // $condition['bool']['should'][] = ['wildcard' => ['content' => ['value' =>'*'. strtolower($item).'*']] ];
                        // $condition['bool']['should'][] = ['match_phrase_prefix' => ['content' => ['query' => $item,'max_expansions'=>50]] ];
                    }

                    $param['body']['query']['bool']['must'][] = $condition;
                }
            }
        }

        // 处理范围
        foreach ($rules as $rule) {
            if (isset($rule['from']) && isset($rule['to'])) {
                $range = [
                    'range' => [
                        $rule['field'] => []
                    ]
                ];
                if ($rule['from'] > 0) {
                    $range['range'][$rule['field']]['gte'] = $rule['from'];
                }

                if ($rule['to'] > 0) {
                    $range['range'][$rule['field']]['lte'] = $rule['to'];
                }

                $param['body']['query']['bool']['must'][] = $range;
            }

            if (isset($rule['behavior']) && $rule['behavior'] == false) {
                if ($rule['field'] == 'level') {
                    $condition = [
                        'bool' => [
                            'should' => []
                        ]
                    ];

                    $levels = explode('、', $rule['value']);

                    $condition['bool']['should'][] = ['term' => ['level' => '']];

                    foreach ($levels as $level) {
                        $condition['bool']['should'][] = ['term' => ['level' => $level]];
                    }

                    $param['body']['query']['bool']['must'][] = $condition;
                }
            }
        }

    //    print_r($param);exit;

        return $this->client->search($param);
    }
}
